package com.supcalls.shiro;

import com.supcalls.entity.User;
import com.supcalls.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author shrek
 * @version 1.0
 */
@Component
public class UsernameRealm extends AuthorizingRealm {

    private final UserMapper userMapper;

    @Autowired
    public UsernameRealm(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        // 得到用户名
        String username = token.getUsername();
        // 根据用户名查询用户信息
        User user = userMapper.selectByUsername(username);

        if (user != null) {
            if (user.getLockState() == 1) {
                throw new AuthenticationException("账号已被锁定，禁止登录！");
            }

            return new SimpleAuthenticationInfo(user, user.getPassword(), username);
        } else {
            throw new AuthenticationException("登录失败，用户名不存在！");
        }
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permissions = new HashSet<>();

        permissions.add("user:delete");
        //permissions.add("user:update");

        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

}